/*
 * @Author: your name
 * @Date: 2021-10-11 11:12:23
 * @LastEditTime: 2021-11-05 14:40:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \datav\src\api\request.js
 */
import axios from "axios";
import { httpUrl } from "./config"
// import main from "../../main"
import router from '../router'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  //   withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (localStorage.getItem("token")) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers["Authorization"] = localStorage.getItem("token");
    }

    // config.headers["Content-Type"] = "application/json";
    config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    if(res.code == 401 || res.code == 402){
      // Toast(res.message)
      router.push('/')
      return
    }
    if (res.code !== 200) {
      // Toast(res.message);
    }

    return res;
  },
  (error) => {
    console.log("err" + error); // for debug
    // return Promise.reject(error)
  }
);

//
export const request = ({
  url,
  body = null,
  method = "get",
  other = {},
  customToast = false,
}) => {
  return new Promise((success, error) => {
    service({
      method: method,
      params: body,
      url: url.indexOf('http') === 0 ? url : httpUrl + url,
      // data: JSON.stringify(body),
      headers: {
        ...other,
      },
    })
      .then((res) => {
        if (res.code == 0) {
          success(res);
        } else if (customToast) {
          // Toast(res.message);
        }
      })
      .catch((res) => {
        error(res);
      });
  });
};

export const jsonp = (url) => {
  if(!url){
      console.error('请传入一个url参数')
      return;
  }
  return new Promise((resolve) => {
    window.jsonCallBack =(result) => {
      resolve(result)
    }
    var JSONP=document.createElement("script");
    JSONP.type="text/html";
    JSONP.src=`${url}&callback=jsonCallBack`;
    document.getElementsByTagName("head")[0].appendChild(JSONP);
    setTimeout(() => {
      document.getElementsByTagName("head")[0].removeChild(JSONP)
    },500)
  })
} 

export default request;
